package com.ma4567.remotecontroller.UserManageRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ma4567.remotecontroller.MysqlHelper.TableLogManager;
import com.ma4567.remotecontroller.MysqlHelper.TableRequestLog;
import com.ma4567.remotecontroller.RemoteControllerApplication;
import com.ma4567.remotecontroller.ffmpegManager.ffmpegController;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;

@CrossOrigin
@RestController
public class UpdataUserPermission {
    @RequestMapping(value = "/api/updataUserPermission", method = RequestMethod.GET)
    public String updateUserPermission(HttpServletRequest request,
                                       @RequestParam("cookie") String Cookie,
                                       @RequestParam("userAccount") int userAccount,
                                       @RequestParam("permission") boolean permission,
                                       @RequestParam("permissionName") String permissionName) throws SQLException {
        ffmpegController.StopStream();
        TableRequestLog.AddLog("Change user " + permissionName + " with " + permission, Cookie, request.getRemoteAddr(), userAccount);
        if(!RemoteControllerApplication.userManager.JudgeCookie(Cookie)){//鉴cookie
            return JSONObject.toJSONString(new getUserListResponse(1, null), SerializerFeature.PrettyFormat);
        }
        else {
            if(!RemoteControllerApplication.userManager.GetUserSingleItemPermission(Cookie, "Root")){//鉴权
                return JSONObject.toJSONString(new getUserListResponse(2, null), SerializerFeature.PrettyFormat);
            }
            else {
                RemoteControllerApplication.userManager.UpdataUserPermission(userAccount, permissionName, permission);
                TableLogManager.AddLog("Change user " + permissionName + " with " + permission, Cookie, userAccount);
                return JSONObject.toJSONString(new getUserListResponse(0, RemoteControllerApplication.userManager.GetAllUser()), SerializerFeature.PrettyFormat);
            }
        }
    }
}
